package com.horsen.service.aliyun.controller.admin;

import com.aliyuncs.exceptions.ClientException;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.horsen.common.util.R;
import com.horsen.common.util.ResultCodeEnum;
import com.horsen.service.aliyun.service.VideoService;
import com.horsen.service.base.exception.HseduException;
import com.horsen.service.base.util.ExceptionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * 文件 控制器
 *
 * @author Horsen
 */
@Api(tags = "阿里云VOD视频管理")
@Slf4j
@RestController("AdminVideo")
@RequestMapping("/admin/aliyun/vod")
public class VideoController {
    @Autowired
    private VideoService videoService;

    @ApiOperationSupport(order = 1)
    @ApiOperation("上传视频至阿里云VOD")
    @PostMapping("/")
    public R upload(@ApiParam(value = "文件", required = true) MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            String videoId = videoService.upload(inputStream, filename);
            return R.ok("视频上传成功").setData("videoId", videoId);
        } catch (Exception e) {
            log.error(ExceptionUtils.getMessage(e));
            // 抛出视频上传错误
            throw new HseduException(ResultCodeEnum.VIDEO_UPLOAD_TOMCAT_ERROR);
        }
    }


    @ApiOperationSupport(order = 2)
    @ApiOperation("从阿里云VOD删除视频")
    @DeleteMapping("/{videoId}")
    public R delete(@ApiParam(value = "视频ID", required = true)
                    @PathVariable String videoId) {
        System.out.println(videoId);
        try {
            videoService.deleteVideo(videoId);
            return R.ok("从VOD删除视频成功");
        } catch (ClientException e) {
            log.error(ExceptionUtils.getMessage(e));
            // 抛出删除视频错误
            throw new HseduException(ResultCodeEnum.VIDEO_DELETE_ALIYUN_ERROR);
        }
    }
}
